package com.chebaohui.iqs.service.impl;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.fastjson.JSONObject;
import com.chebaohui.iqs.config.CompanyCode;
import com.chebaohui.iqs.config.ResultCode;
import com.chebaohui.iqs.entity.Paramter;
import com.chebaohui.iqs.entity.Result;
import com.chebaohui.iqs.entity.base.Cars;
import com.chebaohui.iqs.entity.base.Company;
import com.chebaohui.iqs.entity.db.DbParam;
import com.chebaohui.iqs.entity.interfance.LibaoDelivery;
import com.chebaohui.iqs.entity.req.CarPays;
import com.chebaohui.iqs.entity.req.CarPermit;
import com.chebaohui.iqs.entity.req.CarPrice;
import com.chebaohui.iqs.entity.req.CheckCar;
import com.chebaohui.iqs.entity.res.CompanyCarPermit;
import com.chebaohui.iqs.entity.res.CompanyCarPrice;
import com.chebaohui.iqs.entity.res.CompanyCars;
import com.chebaohui.iqs.service.DBService;
import com.chebaohui.iqs.service.PriceService;
import com.chebaohui.iqs.service.impl.deal.CarCheckCompanys;
import com.chebaohui.iqs.service.impl.deal.CarPriceCompanys;
import com.chebaohui.iqs.service.impl.deal.test.TestConfirm;
import com.chebaohui.iqs.service.impl.deal.test.TestPay;
import com.chebaohui.iqs.service.impl.deal.util.CompanyUtil;
import com.chebaohui.iqs.service.impl.deal.util.InsuranceUtil;
import com.chebaohui.iqs.service.impl.deal.util.LicenseUtil;
import com.chebaohui.iqs.service.impl.deal.util.OwnerUtil;
import com.chebaohui.iqs.service.impl.deal.util.StringUtil;

@Service
public class PriceServiceImpl implements PriceService {
	/**
	 * log:日志输出
	 */
	private Log log = LogFactory.getLog(PriceServiceImpl.class);

	@Autowired
	private DBService db;

	/**
	 * 查车
	 */
	@Override
	public Result<List<CompanyCars<List<Cars>>>> carCheck(Paramter<CheckCar> param) {
		try {

			// 第一步判断保险公司编码参数
			for (Company c : param.getData().getCompanys()) {
				if (null == CompanyUtil.dealCompany(c.getCompanyCode()))
					return new Result<List<CompanyCars<List<Cars>>>>(ResultCode.L02, "保险公司编码错误:" + c.getCompanyCode());
			}
			// 第二步判断车型查询必要参数:车架号(17位大写字母加数字组合)、厂牌型号(4位及以上大写字母加数字加中文字符，不含空格及特殊字符)
			if (!CompanyUtil.valFrameNo(param.getData().getLicense().getFrameNo()))
				return new Result<List<CompanyCars<List<Cars>>>>(ResultCode.L02,
						"车架号错误:" + param.getData().getLicense().getFrameNo());
			if (!CompanyUtil.valLableNo(param.getData().getLicense().getLableNo()))
				return new Result<List<CompanyCars<List<Cars>>>>(ResultCode.L02,
						"厂牌型号错误:" + param.getData().getLicense().getLableNo());

			param.getData().getLicense().setLableNo(CompanyUtil.labelNoDeal(param.getData().getLicense().getLableNo()));

			return new Result<List<CompanyCars<List<Cars>>>>(ResultCode.SUCCESS, new CarCheckCompanys().check(param));

		} catch (Exception e) {
			return new Result<List<CompanyCars<List<Cars>>>>(ResultCode.N02,
					"PriceServiceImpl.carCheck异常:" + e.getMessage());
		}
	}

	/**
	 * 算费
	 */
	@Override
	public Result<List<CompanyCarPrice>> carPrice(Paramter<CarPrice> param) {
		try {

			// 第一步判断保险公司编码参数
			for (Company c : param.getData().getCompanys()) {
				if (null == CompanyUtil.dealCompany(c.getCompanyCode()))
					return new Result<List<CompanyCarPrice>>(ResultCode.L02, "保险公司编码错误:" + c.getCompanyCode());
				if (StringUtil.isNulls(c.getModelCode()))
					return new Result<List<CompanyCarPrice>>(ResultCode.L02, "保险公司车型编码空:null");
			}

			// 第二步判断车主信息参数
			String dealO = OwnerUtil.deal(param.getData().getOwner(), 0);
			if (!"true".equals(dealO))
				return new Result<List<CompanyCarPrice>>(ResultCode.L02, "车主信息," + dealO);

			// 第三步判断行驶证参数
			String dealL = LicenseUtil.deal(param.getData().getLicense());
			if (!"true".equals(dealL))
				return new Result<List<CompanyCarPrice>>(ResultCode.L02, "行驶证," + dealL);

			// 第四步判断车险选择参数
			String dealI = InsuranceUtil.deal(param.getData().getInsuranceList());
			if (!"true".equals(dealI))
				return new Result<List<CompanyCarPrice>>(ResultCode.L02, "车险选择," + dealI);

			List<CompanyCarPrice> result = new CarPriceCompanys().price(param);

			log.info(param.getData().getLicense().getFrameNo() + "," + param.getData().getLicense().getEngineNo()
					+ "；算费结果：" + JSONObject.toJSONString(result));// 后台输出信息
			boolean check = true;

			for (CompanyCarPrice r : result) {
				if (r.getCode().equals(ResultCode.SUCCESS.getCode())) {
					check = false;
				} else {
					if (r.getMsg().indexOf("重复投保") > -1 || r.getMsg().indexOf("交强险终保时间必须大于等于起保日期")>-1 || r.getMsg().indexOf("商业险终保时间必须大于等于起保日期")>-1) {
						r.setCode(ResultCode.N04.getCode());
						r.setMsg(ResultCode.N04.getMsg() + "车险重复投保或到期时间大于90天");//循环不成功 就重新出错误信息
					} else {
						r.setCode(ResultCode.N08.getCode());
						r.setMsg(ResultCode.N08.getMsg());
					}
				}
			}
			if (check) {
				Result<List<CompanyCarPrice>> res = new Result<List<CompanyCarPrice>>(ResultCode.N08, "");
				res.setData(result);
				if (result.size() == 1) {
					res.setCode(result.get(0).getCode());
					res.setMsg(result.get(0).getMsg());
				}
				return res;
			} else
				return new Result<List<CompanyCarPrice>>(ResultCode.SUCCESS, result);
		} catch (Exception e) {
			log.error(param.getData().getLicense().getFrameNo() + "," + param.getData().getLicense().getEngineNo()
					+ ",PriceServiceImpl.carPrice异常," + e.getMessage());
			return new Result<List<CompanyCarPrice>>(ResultCode.N08, "");
		}
	}

	/**
	 * 核保
	 */
	@Override
	public Result<CompanyCarPermit> carConfirm(Paramter<CarPermit> param) {
		if (param.getData().getCompanyCode().equals(CompanyCode.TEST.getClass())) {
			return new Result<CompanyCarPermit>(ResultCode.SUCCESS, TestConfirm.confirm(param.getData()));
		}
		// if
		// (param.getData().getCompanyCode().equals(CompanyCode.LIBAO.getClass()))
		// {
		// try {
		// DbParam dbParam=new DbParam();
		// dbParam.setcType("insurance");
		// dbParam.setNumType("json");
		// dbParam.setReserve(param.getData().getCarOrder().getOrederNo());
		//
		// List<DbParam> res = db.query(dbParam);
		// if (null == res || res.isEmpty() || res.size() < 1) {
		// return new Result<CompanyCarPermit>(ResultCode.N02,"错误:无报价记录");
		// }
		//
		// return new Result<CompanyCarPermit>(ResultCode.SUCCESS,
		// LbConfirm.confirm(res.get(0), param.getData()));
		// } catch (Exception e) {
		// return new
		// Result<CompanyCarPermit>(ResultCode.N02,"异常:"+e.getMessage());
		// }
		// }
		return new Result<CompanyCarPermit>(ResultCode.N03);
	}

	/**
	 * 支付登记
	 */
	@Override
	public Result<CompanyCarPermit> carPay(Paramter<CarPays> param) {
		if (param.getData().getCompanyCode().equals(CompanyCode.TEST.getClass())) {
			return new Result<CompanyCarPermit>(ResultCode.SUCCESS, TestPay.permit(param.getData()));
		}
		if (param.getData().getCompanyCode().equals(CompanyCode.LIBAO.getClass())) {
			// LbPayRegister register=new LbPayRegister(param.getData());
			// try {
			// CompanyCarPermit res=register.register();
			// DbParam dbParam=register.getDbParam();
			// db.add(dbParam);
			// return new Result<CompanyCarPermit>(ResultCode.SUCCESS,res);
			// } catch (Exception e) {
			// return new
			// Result<CompanyCarPermit>(ResultCode.N02,"异常:"+e.getMessage());
			// }
		}
		return new Result<CompanyCarPermit>(ResultCode.N03);
	}

	@Override
	public void backDeal(final HttpServletRequest request, final HttpServletResponse response, String type) {
		if ("libao".equals(type)) {
			LibaoDelivery res = new LibaoDelivery();
			res.setStatus(true);
			res.setResultCode("0");
			res.setResultMessage("收到配货回调信息");
			JSONObject req = getParamJson(request.getParameterMap());
			res.setFlowId(req.getString("flowId"));
			res.setUuId(req.getString("access_token"));
			res.setPdk(req.getString("pdk"));
			setResponseText(response, res.toString());
		}
	}

	/**
	 * 请求参数转json
	 * 
	 * @param param
	 * @return
	 */
	private JSONObject getParamJson(Map<String, String[]> param) {
		try {
			if (null == param || param.isEmpty())
				return null;

			JSONObject res = new JSONObject();
			for (Map.Entry<String, String[]> entry : param.entrySet())
				res.put(entry.getKey(), entry.getValue()[0]);
			return res;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * setResponseText:(返回值设置). <br/>
	 * 
	 * @author xielonghai
	 * @param text
	 * @since JDK 1.7
	 */
	private void setResponseText(HttpServletResponse response, String text) {
		PrintWriter writer = null;
		try {
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);

			response.setContentType("text/plain");
			response.setCharacterEncoding("UTF-8");
			writer = response.getWriter();
			writer.write(text);
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (writer != null)
				writer.close();
		}
		return;
	}

	@Override
	public ModelAndView libaoPay(String libaoFlowId) {
		try {
			if (StringUtil.isNulls(libaoFlowId))
				return errorFront("支付页面请求参数错误...libaoFlowId为空");

			DbParam dbParam = new DbParam();
			dbParam.setcType("insurance");
			dbParam.setNumType("libao-pay");
			dbParam.setReserve(libaoFlowId);
			List<DbParam> res = db.query(dbParam);
			if (null == res || res.isEmpty() || res.size() < 1) {
				log.error(libaoFlowId + "没有发现该libaoFlowId的订单号...");
				return errorFront("没有查询到此订单的支付信息.");
			}

			JSONObject pay = JSONObject.parseObject(res.get(0).getDatas());

			log.info(libaoFlowId + ",读取缓存支付记录:" + pay);

			ModelAndView view = new ModelAndView("libao/pays");
			StringBuffer html = new StringBuffer();
			html.append("<form id=\"subform\" hidden=\"hidden\"  action=\"" + pay.getString("formAction")
			+ "\" method=\"post\">");
			for (String name : pay.keySet()) {
				if (!"libaoFlowId".equals(name) && !"formAction".equals(name) && !"timeLongTo".equals(name)) {
					html.append("<input type=\"text\" name=\"" + name + "\" value=\"" + pay.getString(name) + "\" />");
				}
			}
			html.append("</form>");
			log.info(libaoFlowId + ",支付页面:" + html.toString());

			view.addObject("obj", html.toString());
			return view;
		} catch (Exception e) {
			return errorFront("订单异常:" + e.getMessage());
		}

	}

	/**
	 * 错误页面
	 * 
	 * @param error
	 * @return
	 */
	private ModelAndView errorFront(String error) {
		ModelAndView view = new ModelAndView("libao/err");
		view.addObject("error", error);// 错误信息
		return view;
	}
}
